package com.lyl.syt.controller;

import cn.hutool.core.util.StrUtil;
import com.lyl.syt.common.result.Result;
import com.lyl.syt.service.MsmService;
import com.lyl.syt.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "短信服务")
@RestController
@RequestMapping("/api/msm")
@RequiredArgsConstructor
public class MsmController {
    private final MsmService aliYunSmsService;
    private final RedisTemplate<String,String> redisTemplate;

    public static final String MSM_PREFIX = "yygh::msm_phone_code::";

    @ApiOperation("发送短信验证码")
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //1. 从redis中获取验证码，如果获取成功，直接返回
        String code = redisTemplate.opsForValue().get(MSM_PREFIX + phone);
        if (StrUtil.isNotBlank(code)){
            return Result.ok();
        }

        //2. 如果获取不到，生成验证码，通过整合短信服务进行发送，
        code = RandomUtil.getSixBitRandom();
        //整合短信服务，发送验证码短信
        boolean isSend = aliYunSmsService.send(phone,code);
        // 生成验证码放入到redis中，并设置有效时间
        if (isSend){
            redisTemplate.opsForValue().set(MSM_PREFIX + phone , code,2, TimeUnit.MINUTES);
            return Result.ok();
        }
        return Result.fail().message("发送短信失败");
    }

}
